package cn.tedu.storage.tcc;

import cn.tedu.storage.entity.Storage;
import cn.tedu.storage.mapper.StorageMapper;
import io.seata.rm.tcc.api.BusinessActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
@Component
public class StorsgeTccActionImpl implements StorsgeTccAction {
  @Autowired
    private StorageMapper storageMapper;

  @Transactional
    @Override
    public boolean prepare(BusinessActionContext ctx, Long productId, Integer count) {
      Storage storage = storageMapper.selectByProductId(productId);
      if (storage.getResidue() < count){
          throw new RuntimeException("库存不足");
      }
      storageMapper.updateFrozenToResidue(productId, count);
      return true;
  }
    @Transactional
    @Override
    public boolean commit(BusinessActionContext ctx) {
        Long productId =
                Long.valueOf(ctx.getActionContext("productId").toString());
        Integer count =
                Integer.valueOf(ctx.getActionContext("count").toString());
        storageMapper.updateFrozenToUsed(productId,count);
        return true;
    }
    @Transactional
    @Override
    public boolean rollback(BusinessActionContext ctx) {
        Long productId =
                Long.valueOf(ctx.getActionContext("productId").toString());
        Integer count =
                Integer.valueOf(ctx.getActionContext("count").toString());
        storageMapper.updateFrozenToResidue(productId,count);
        return true;
    }
}
